<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search_area">
      <uni-search-bar @confirm="search" @input="input" placeholder="搜索宠物、知识、商品" />
    </view>

    <!-- 轮播图区域 -->
    <view class="hot_pet">
      <view class="section-header">
        <text class="pet_cate_title">热门推荐</text>
      </view>
      <swiper class="swiper-box" indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000"
        :circular="true" indicator-color="rgba(255,255,255,0.6)" indicator-active-color="#ffffff">
        <swiper-item v-for="(item, i) in swiper_list" :key="item._id" class="swiper-item">
          <navigator class="swiper_pic" :url="item.link || '/pages/detail/detail?id=' + item._id">
            <image :src="item.url" mode="aspectFill" lazy-load></image>
            <view class="swiper-title">{{item.title}}</view>
          </navigator>
        </swiper-item>
      </swiper>
    </view>

    <!-- 异宠新闻区域 -->
    <view class="pet_news">
      <view class="section-header">
        <text class="pet_cate_title">异宠新闻</text>
        <text class="more" @click="goToMore('news')">更多</text>
      </view>
      <view class="news-list">
        <view class="news-items">
          <view class="news-item" v-for="(item, index) in newsList" :key="index" @click="goToNewsDetail(item.id)">
            <image :src="item.image" mode="aspectFill" class="news-image"></image>
            <view class="news-info">
              <text class="news-title">{{item.title}}</text>
              <view class="news-meta">
                <uni-dateformat :date="Number(item.date)" format="yyyy-MM-dd"
                  :threshold="[0,3600*24*30]"></uni-dateformat>
                <text class="news-views">{{item.views}}阅读</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 异宠分类区域 -->
    <view class="pet_cate">
      <view class="section-header">
        <text class="pet_cate_title">异宠分类</text>
      </view>
      <view class="pet_grid">
        <view class="pet_item" v-for="(item, index) in pet_cat_info" :key="index" @click="go_cate(item)">
          <image :src="item.path" mode="aspectFit" lazy-load></image>
          <text>{{item.name}}</text>
        </view>
      </view>
    </view>

    <!-- 养宠基础知识区域 -->
    <view class="pet_cate">
      <view class="section-header">
        <text class="pet_cate_title">养宠基础知识</text>
      </view>
      <view class="pet_grid">
        <view class="pet_item" v-for="(item, index) in pet_feed_info" :key="index" @click="goToGuide(item)">
          <image :src="item.path" mode="aspectFit" lazy-load></image>
          <text>{{item.name}}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    mapActions
  } from 'pinia'
  import {
    usePetStore
  } from '@/stores/store'
  import {
    getCateList
  } from '@/utils/category'

  const petStore = usePetStore();

  export default {
    data() {
      return {
        swiper_list: [],
        pet_cat_info: [],
        pet_feed_info: [],
        newsList: [],
      }
    },
    onLoad() {
      this.get_swiper_list();
      this.get_news_list();
      this.getCategoryList();
      this.getKnowledgeList();
    },
    methods: {
      ...mapActions(usePetStore, ['setCurrentCategory']),

      async get_swiper_list() {
        try {
          const res = await uniCloud.importObject('fetch_data').getSwiperData();
          if (res.errCode === 0) {
            this.swiper_list = res.data;
          } else {
            throw new Error(res.errMsg);
          }
        } catch (error) {
          console.error('获取轮播图失败：', error);
          uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      },

      async get_news_list() {
        try {
          const res = await uniCloud.importObject('fetch_data').getNewsList({
            page: 1,
            pageSize: 3
          });
          if (res.errCode === 0) {
            this.newsList = res.data;
          } else {
            throw new Error(res.errMsg);
          }
        } catch (error) {
          console.error('获取新闻列表失败：', error);
          uni.showToast({
            title: '获取新闻失败',
            icon: 'none'
          });
        }
      },

      async getCategoryList() {
        try {
          const categories = await getCateList();
          this.pet_cat_info = categories.map(item => ({
            path: item.category_pic,
            name: item.category,
            id: item._id
          }));
        } catch (error) {
          console.error('获取分类列表失败：', error);
          uni.showToast({
            title: '获取分类失败',
            icon: 'none'
          });
        }
      },

      async getKnowledgeList() {
        try {
          const res = await uniCloud.importObject('fetch_data').getKnowledgeList();
          if (res.errCode === 0) {
            this.pet_feed_info = res.data.map(item => ({
              path: item.knowledge_pic,
              name: item.category,
              id: item._id
            }));
          } else {
            throw new Error(res.errMsg);
          }
        } catch (error) {
          console.error('获取知识列表失败：', error);
          uni.showToast({
            title: '获取知识列表失败',
            icon: 'none'
          });
        }
      },

      go_cate(item) {
        this.setCurrentCategory(item.name);
        uni.switchTab({
          url: '/pages/cate/cate'
        });
      },

      goToGuide(item) {
        uni.navigateTo({
          url: `/pages/guide/guide?id=${item.id}`
        });
      },

      goToMore(type) {
        if (type === 'news') {
          uni.navigateTo({
            url: '/pages/news/news'
          });
        }
      },

      search(e) {
        const keyword = e.value;
        if (!keyword.trim()) return;
        uni.navigateTo({
          url: `/pages/search/search?keyword=${encodeURIComponent(keyword)}`
        });
      },

      input(e) {
        // 可以在这里添加搜索建议功能
      },

      goToNewsDetail(id) {
        uni.navigateTo({
          url: '/pages/news/detail?id=' + id
        });
      },
    }
  }
</script>

<style lang="scss">
  .container {
    padding-bottom: 30rpx;
    background: #f5f5f5;
    min-height: 100vh;

    .search_area {
      background: #fff;
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;

      .pet_cate_title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }

      .pet_news .more {
        font-size: 24rpx;
        color: #666;
      }
    }

    .hot_pet {
      margin: 10rpx;
      background: #fff;
      border-radius: 16rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

      .swiper-box {
        height: 360rpx;
        margin: 0 20rpx;

        .swiper-item {
          border-radius: 12rpx;
          overflow: hidden;

          .swiper_pic {
            position: relative;
            width: 100%;
            height: 100%;

            image {
              width: 100%;
              height: 100%;
              border-radius: 12rpx;
            }

            .swiper-title {
              position: absolute;
              bottom: 0;
              left: 0;
              right: 0;
              padding: 20rpx;
              color: #fff;
              font-size: 28rpx;
              background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
            }
          }
        }
      }
    }

    .pet_news {
      margin: 20rpx;
      background: #fff;
      border-radius: 16rpx;
      padding: 20rpx 0;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

      .news-list {
        //margin-top: 20rpx;
        background-color: #fff;
        border-radius: 12rpx;
        //padding: 20rpx;

        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          //margin-bottom: 20rpx;

          .title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
          }

          .more {
            font-size: 24rpx;
            color: #999;
          }
        }

        .news-items {
          .news-item {
            display: flex;
            padding: 20rpx 0;
            border-bottom: 1rpx solid #eee;

            &:last-child {
              border-bottom: none;
            }

            .news-image {
              width: 200rpx;
              height: 150rpx;
              border-radius: 8rpx;
              margin-right: 20rpx;
            }

            .news-info {
              flex: 1;
              display: flex;
              flex-direction: column;
              justify-content: space-between;

              .news-title {
                font-size: 28rpx;
                color: #333;
                line-height: 1.4;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
              }

              .news-meta {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 24rpx;
                color: #999;
                margin-top: 10rpx;

                .news-date {
                  color: #999;
                }

                .news-views {
                  color: #999;
                }
              }
            }
          }
        }
      }
    }

    .pet_cate {
      margin: 20rpx;
      background: #fff;
      border-radius: 16rpx;
      padding: 20rpx 0;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

      .pet_grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 20rpx;
        padding: 0 20rpx;

        .pet_item {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 16rpx;
          transition: all 0.3s ease;

          &:active {
            transform: scale(0.95);
          }

          image {
            width: 100rpx;
            height: 100rpx;
            margin-bottom: 12rpx;
          }

          text {
            font-size: 24rpx;
            color: #333;
            text-align: center;
            line-height: 1.4;
          }
        }
      }
    }
  }
</style>